package cn.wizzer.app.web.commons.ext.websocket.action.msg.group;

import cn.wizzer.app.user.modules.models.GroupInfo;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.GroupInfoService;
import cn.wizzer.app.user.modules.services.GroupMemberService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.param.Param;
import cn.wizzer.framework.util.param.Param4Map;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

/**
 * @author zl
 * @date 2020/6/5 15:25
 */
@IocBean
@NettyAction(uri = "/group/add/member", filters = {TokenFilter.class})
public class GroupAddMemberAction extends BaseNettyAction {

    @Inject
    @Reference
    private GroupInfoService groupInfoService;

    @Inject
    @Reference
    private GroupMemberService groupMemberService;

    @Inject
    @Reference
    private UserService userService;

    @Override
    public Result action(Channel income,
                         @Param4Map(fields = {@Param(name = "groupId", required = true),
                                 @Param(name = "phone", required = true)}) JSONObject params) {
        ChatUserVO self = NettyCache.globalGet(params.get("appid"));
        String groupId = params.getString("groupId");
        User user = userService.fetch(Cnd.where("phone", "=", params.getString("phone")));
        if (user == null) {
            Result.breakWith("该用户不存在");
        }
        GroupInfo groupInfo = groupInfoService.fetch(Cnd.where("id", "=", groupId).and("masterId", "=", self.getId()));
        if (groupInfo == null) {
            Result.breakWith("添加失败，你不是群主或群组不存在");
        }
        //添加群成员
        groupMemberService.addMember(user.getId(), groupId);
        //若被邀请用户在线则通知用户
        ChatUserVO beInvitedUser = NettyCache.globalGet(user.getId());
        if (beInvitedUser != null) {
            String content = "您已加入群 " + groupInfo.getGroupName() + " 快和大家打招呼吧";
            NettyMsgUtil.send(beInvitedUser.getChannel(), ChatResult.MessageTypeEnum.SYSTEM, ChatResult.ActionEnum.JOIN, self, content);
        }
        return Result.success();
    }
}
